const { startTasksAsync, stopTaskAsync, startSpiderMainThread, getSpiderWindow } = require("./spider");
const { ipcMain, BrowserWindow } = require('electron')
const { initConnection, dbQuery } = require("./common/db");
const { initService } = require("./service");
const { init : initCronService } = require("./service/cronService");
const fs = require("fs");

var mainWindow = null;
var connection = null;
var isInit = false;

async function appRun() {
    if (!isInit) {
        await init();
        isInit = true;
    }
    try {
        var result = await dbQuery("select stc.*, st.* from spider_task st left join spider_task_config stc on st.task_id = stc.task_id  where st.task_status = '1' order by start_datetime asc");
        if (result.success && result.data && result.data.length > 0) {
            showLog("待采集的任务列表：");
            for (var i = 0; i < result.data.length; i++) {
                var task = result.data[i];
                showLog(`${i + 1}:${task.task_name}`);
            }
            var tasks = result.data;
            await startTasksAsync(tasks);
            console.log("appRun", result)
            appRun();
        } else {
            if (!result.success) {
                showLog("获取待采集的任务列表异常：" + result.error);
            } else {
                showLog("获取待采集的任务列表为空!", "debug");
            }
            setTimeout(function () {
                appRun();
            }, 1000 * 3);
        }
    } catch (e) {
        console.log("运行过程异常！", e);
        setTimeout(function () {
            appRun();
        }, 1000 * 3);
    }
}
function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 1200,
        height: 900,
        autoHideMenuBar : true,
        webPreferences: {
            nodeIntegration: true,
            nodeIntegrationInWorker: true,
            nodeIntegrationInSubFrames: true,
            enableRemoteModule: true,
            contextIsolation: false,
        }
    })
    mainWindow.maximize();
    // and load the index.html of the app.
    mainWindow.loadFile('app/views/index.html')
    // mainWindow.webContents.openDevTools()
    return mainWindow;
}

async function init() {
    await initConnection('sqlite');
    initService();
    mainWindow = createWindow();
    startSpiderMainThread(mainWindow);
    initCronService(mainWindow);
    ipcMain.on('switchSpiderWindow', function (event) {
        switchSpiderWindow();
    });
    ipcMain.on('loadComponents', function (event, arg) {
        event.returnValue = loadComponents("/views/component");
    })
    ipcMain.on("taskAction", async function (event, arg) {
        console.log('taskAction', arg)
        if (arg.oper == 'start') {
            await dbQuery("update spider_task set task_status = ?, start_datetime = NOW() where task_id = ?", [1, arg.task.task_id])
            event.returnValue = { success: true };
        } else if (arg.oper == 'stop') {
            var result = await stopTaskAsync(arg.task)
            event.returnValue = result
        }
    })

    ipcMain.on("taskActionAll", async function (event, arg) {
        console.log('taskActionAll', arg)
        if (arg.oper == 'start') {
            await dbQuery("update spider_task set task_status = ?, start_datetime = NOW() where task_status in (0,4,5,7)", [1])
            event.returnValue = { success: true };
        } else if (arg.oper == 'stop') {
            var result = await stopTaskAsync(arg.task)
            event.returnValue = result
        }
    })
    ipcMain.on("toggleDevTools", async function (event, arg) {
        mainWindow.webContents.toggleDevTools();
        event.returnValue = true;
    })
}

function loadComponents(dir) {
    var finalDir = __dirname + dir;
    console.log("dir", finalDir)
    var files = fs.readdirSync(finalDir);
    var components = [];
    files.forEach((file) => {
        var stats = fs.statSync(finalDir + '/' + file);
        if (stats.isFile()) {
            components[components.length] = {
                key: file.substring(0, file.length - 3),
                content: fs.readFileSync(finalDir + '/' + file, { encoding: 'utf-8' })
            }
        } else {
            components = components.concat(loadComponents(dir + '/' + file));
        }
    })
    return components;
}


function switchSpiderWindow() {
    console.log(getSpiderWindow())
    if (getSpiderWindow().isVisible()) {
        getSpiderWindow().hide();
    } else {
        getSpiderWindow().show();
    }
    console.log('switchSpiderWindow')
}

function showLog(msg, type) {
    mainWindow.webContents.send("log", { msg: msg, type: type });
}

module.exports = {
    appRun: appRun,
}
